Strings¶

In [1]:
'this is a string'
Out[1]:
'this is a string'

🎨 len¶

In [3]:
len('word and word')
Out[3]:
13

You can use len to get the length of a string.

🖌 Building Strings¶

In [4]:
'fire' + 'place'
Out[4]:
'fireplace'
In [5]:
'yo' * 2
Out[5]:
'yoyo'
In [6]:
'nan ' * 16 + 'batman!'
Out[6]:
'nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan batman!'
batman!

🖌 +=¶

In [7]:
message = 'Hello'
message = message + ' world!'
message
Out[7]:
'Hello world!'
In [8]:
message = 'Hello'
message += ' world!'
message
Out[8]:
'Hello world!'

🖌 String Iteration¶

In [9]:
for letter in 'this is a string':
    print(letter)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g

🎨 Character classes¶

In [10]:
'a'.isalpha(), '8'.isalpha()
Out[10]:
(True, False)
In [11]:
'abcdefg'.isalpha(), 'abc1234'.isalpha(), 'abc!'.isalpha()
Out[11]:
(True, False, False)
In [12]:
'a'.isdigit(), '8'.isdigit()
Out[12]:
(False, True)
In [13]:
'12345'.isdigit(), '12345pi'.isdigit(), '123.456'.isdigit()
Out[13]:
(True, False, False)
In [14]:
'a'.isalnum(), '8'.isalnum()
Out[14]:
(True, True)
In [15]:
'12345'.isalnum(), '12345pi'.isalnum(), '123.456'.isalnum()
Out[15]:
(True, True, False)
In [16]:
'a'.isspace(), '8'.isspace(), ' '.isspace()
Out[16]:
(False, False, True)
In [17]:
'A'.islower(), 'A'.isupper()
Out[17]:
(False, True)
In [19]:
'a'.islower(), 'a'.isupper(), '9'.islower()
Out[19]:
(True, False, False)
In [20]:
'a'.upper(), 'a'.lower()
Out[20]:
('A', 'a')
In [21]:
'A'.upper(), 'A'.lower()
Out[21]:
('A', 'a')
In [22]:
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_+=[]{}"\'|:;,./?<> \t\n'
In [23]:
# isalpha
alphas = ''
for character in characters:
    if character.isalpha():
        alphas += character
print(alphas)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
In [24]:
# isdigit
digits = ''
for character in characters:
    if character.isdigit():
        digits += character
print(digits)
0123456789
In [25]:
# isalnum
alphanumeric = ''
for character in characters:
    if character.isalnum():
        alphanumeric += character
print(alphanumeric)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
In [26]:
# isspace
spaces = ''
for character in characters:
    if character.isspace():
        spaces += character
print(spaces)
 	

😶
In [27]:
# isspace
spaces = []
for character in characters:
    if character.isspace():
        spaces.append(character)
print(spaces)
[' ', '\t', '\n']
In [28]:
# other stuff
symbols = ''
for character in characters:
    if not character.isspace() and not character.isalnum():
        symbols += character
print(symbols)
`~!@#$%^&*()-_+=[]{}"'|:;,./?<>
In [29]:
# upper and lower
uppers = ''
lowers = ''
for character in characters:
    if character.isupper():
        uppers += character
    elif character.islower():
        lowers += character
print(uppers)
print(lowers)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

👩🏻‍🎨 No Spaces¶

Write a function that replaces all space characters with dashes.

In [36]:
def no_spaces(text):
    """Replace all space characters with dashes"""
    new_text = ''
    for char in text:
        if char.isspace():
            char = '-'
        new_text += char
    return new_text
In [ ]:
def no_spaces(text):
    result = ''
    for c in text:
        if c.isspace():
            c = '-'
        result += c
    return result
In [37]:
print(no_spaces('BYU is the place to be.'))
BYU-is-the-place-to-be.
In [38]:
message = """This is a long,
multiline string.
It has multiple lines.
That is what "multiline" means. :)"""

print(message)
print()
print(no_spaces(message))
This is a long,
multiline string.
It has multiple lines.
That is what "multiline" means. :)

This-is-a-long,-multiline-string.-It-has-multiple-lines.-That-is-what-"multiline"-means.-:)
In [39]:
print(no_spaces('Goodbye spaces \t tabs \n and newlines'))
Goodbye-spaces---tabs---and-newlines

👨🏾‍🎨 Numbers?¶

Write a function that replaces every number in a string with ?

In [40]:
def no_numbers(text):
    """Replace every number with ?"""
    new_text = ''
    for char in text:
        if char.isdigit():
            char = '?'
        new_text += char
    return new_text
In [ ]:
def no_numbers(text):
    result = ''
    for char in text:
        if char.isdigit():
            result = result + '?'
        else:
            result = result + char
    return result
In [41]:
no_numbers('There were 7 people.')
Out[41]:
'There were ? people.'
In [42]:
no_numbers('15 out of 25 have more than 17.3% contamination.')
Out[42]:
'?? out of ?? have more than ??.?% contamination.'
In [43]:
no_numbers('2 + 2 = 5, for large values of 2.')
Out[43]:
'? + ? = ?, for large values of ?.'

🧑🏻‍🎨 Sum of Digits¶

Add up all the digits found in a string.

In [52]:
def find_digits(text):
    """Return a list of the digits (as ints) from the text"""
    digits = []
    for c in text:
        if c.isdigit():
            digits.append(int(c))
    return digits

    
def add_digits(text):
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    digits = find_digits(text)
    return sum(digits)
In [53]:
def add_digits(text):
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    total = 0
    for c in text:
        if c.isdigit():
            total += int(c)
    return total
In [54]:
add_digits('123foo')
Out[54]:
6
In [55]:
add_digits('10 students ate 6 oranges and 42 students ate 7 pears.')
Out[55]:
20

Key Ideas¶

  • String iteration
  • 'foo' + 'bar', 'BYU! ' * 5
  • .isalpha(), .isdigit(), .isalnum(), .isspace(), .isupper(), .islower()
  • .upper(), .lower()
  • +=